import React, { useEffect } from 'react';
import { Form, Input, Button, message, Card } from 'antd';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { loginStart, loginSuccess, loginFailure } from './authSlice';
import { login } from '@/api/authApi';
import { RootState } from '@/store';

const LoginPage: React.FC = () => {
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { loading, error, isAuthenticated } = useSelector((state: RootState) => state.auth);

  // 登录成功后跳转
  useEffect(() => {
    if (isAuthenticated) {
      navigate('/dashboard');
    }
  }, [isAuthenticated, navigate]);

  // 显示错误信息
  useEffect(() => {
    if (error) {
      message.error(error);
    }
  }, [error]);

  const onFinish = async (values: { username: string; password: string }) => {
    // try {
    //   dispatch(loginStart());
    //   const data = await login(values);
    //   dispatch(loginSuccess(data.user));
    //   message.success('登录成功');
    // } catch (err) {
    //   dispatch(loginFailure('用户名或密码错误'));
    // }

    try {
      dispatch(loginStart());
      const data = await login(values);
      if (data && data.success && data.user) {
        dispatch(loginSuccess(data.user));
        message.success('登录成功');
      } else {
        dispatch(loginFailure(data?.message || '用户名或密码错误'));
        message.error(data?.message || '用户名或密码错误');
      }
    } catch (err) {
      dispatch(loginFailure('用户名或密码错误'));
      message.error('用户名或密码错误');
    }
  };

  return (
    <Card bordered={false}>
      <Form
        form={form}
        name="login_form"
        layout="vertical"
        initialValues={{ username: 'admin', password: 'admin123' }}
        onFinish={onFinish}
      >
        <Form.Item
          name="username"
          label="用户名"
          rules={[{ required: true, message: '请输入用户名' }]}
        >
          <Input placeholder="请输入用户名" />
        </Form.Item>

        <Form.Item
          name="password"
          label="密码"
          rules={[{ required: true, message: '请输入密码' }]}
        >
          <Input.Password placeholder="请输入密码" />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" loading={loading} block size="large">
            登录
          </Button>
        </Form.Item>

        <div style={{ textAlign: 'center', marginTop: 16 }}>
          <p style={{ margin: 0, color: '#666' }}>
            测试账号: admin/admin123 或 user/user123
          </p>
        </div>
      </Form>
    </Card>
  );
};

export default LoginPage;
    